//
//  UPEnumCustomView.m
//  Uang Pasti
//
//  Created by 李永彬 on 2025/8/27.
//

#import "UPEnumCustomView.h"

@interface UPEnumCustomView ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UIImageView *containerImageView;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIButton *confirmButton;
@property (nonatomic, strong) NSIndexPath *selectedIndexPath; // 记录当前选中的cell

@end

@implementation UPEnumCustomView

-(instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        _selectedIndexPath = [NSIndexPath indexPathForRow:0 inSection:0]; // 默认选中第一个
        [self commonInitSubviews];
    }
    return self;
}

- (void)commonInitSubviews {
    // 设置背景图片
    UIImage *bgImage = [UIImage imageNamed:@"address_bg"];
    CGFloat bgAspectRatio = bgImage.size.width / bgImage.size.height;
    CGFloat bgWidth = [UIScreen mainScreen].bounds.size.width - 2 * 16;
    CGFloat bgHeight = bgWidth / bgAspectRatio;
    [self.containerImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self);
        make.centerX.equalTo(self);
        make.height.mas_equalTo(bgHeight);
        make.width.mas_equalTo(bgWidth);
        make.bottom.equalTo(self);
    }];
    
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.containerImageView).offset(20);
        make.leading.equalTo(self.containerImageView).offset(30);
        make.trailing.equalTo(self.containerImageView).offset(-30);
        make.height.mas_equalTo(25);
    }];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.confirmButton.mas_top).offset(-10);
        make.leading.trailing.equalTo(self.containerImageView).inset(40);
        make.top.equalTo(self.titleLabel.mas_bottom).offset(30);
    }];
    
    UIImage *buttonImage = [UIImage imageNamed:@"button_bg_style1"];
    CGFloat buttonHeight = 50.0;
    CGFloat buttonAspectRatio = buttonImage.size.width / buttonImage.size.height;
    CGFloat buttonWidth = buttonHeight * buttonAspectRatio;
    [self.confirmButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self).offset(-bottomsafeArea());
        make.centerX.equalTo(self.containerImageView);
        make.height.mas_equalTo(buttonHeight);
        make.width.mas_equalTo(buttonWidth);
    }];
}

- (UIImageView *)containerImageView {
    if (!_containerImageView) {
        _containerImageView = [[UIImageView alloc] init];
        _containerImageView.contentMode = UIViewContentModeScaleAspectFit;
        _containerImageView.image = [UIImage imageNamed:@"address_bg"];
        _containerImageView.userInteractionEnabled = YES;
        [self addSubview:_containerImageView];
    }
    return _containerImageView;
}

- (UILabel *)titleLabel {
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc] init];
        _titleLabel.font = [UIFont systemFontOfSize:13 weight:400];
        _titleLabel.textColor = [UIColor colorWithHexString:@"#FFFFFF"];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        [self addSubview:_titleLabel];
    }
    return _titleLabel;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell"];
        [_tableView setShouldIgnoreScrollingAdjustment:YES];
        [_tableView setShouldRestoreScrollViewContentOffset:true];
        [self addSubview:_tableView];
    }
    return _tableView;
}

- (UIButton *)confirmButton {
    if (!_confirmButton) {
        _confirmButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_confirmButton setBackgroundImage:[UIImage imageNamed:@"button_bg_style1"] forState: UIControlStateNormal];
        [_confirmButton setTitle:LocalizableForKey(@"Confirm") forState:UIControlStateNormal];
        [_confirmButton setTitleColor:[UIColor colorWithHexString:@"#000000"] forState:UIControlStateNormal];
        [_confirmButton addTarget:self action:@selector(clickConfirmBtnAction) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_confirmButton];
    }
    return _confirmButton;
}

- (void)setPersonalBlackModel:(PersonalBlackModel *)personalBlackModel {
    _personalBlackModel = personalBlackModel;
    self.titleLabel.text = personalBlackModel.musetic;
    
    // 重置选中状态为第一个
    if (personalBlackModel.everyably.count > 0) {
        _selectedIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    } else {
        _selectedIndexPath = nil;
    }
    
    [self.tableView reloadData];
    
    // 滚动到选中的位置
    if (_selectedIndexPath) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView scrollToRowAtIndexPath:self.selectedIndexPath
                                 atScrollPosition:UITableViewScrollPositionMiddle
                                         animated:NO];
        });
    }
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.personalBlackModel.everyably.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell" forIndexPath:indexPath];
    PersonalEveryablyModel *model = self.personalBlackModel.everyably[indexPath.row];
    cell.textLabel.text = model.quindecimlocalety;
    cell.textLabel.textAlignment = NSTextAlignmentCenter;
    cell.backgroundColor = [UIColor clearColor];
    
    // 配置选中状态
    [self configureCell:cell atIndexPath:indexPath];
    
    return cell;
}

- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    if ([indexPath isEqual:self.selectedIndexPath]) {
        cell.textLabel.textColor = [UIColor colorWithHexString:@"#000000"];
        cell.textLabel.font = [UIFont systemFontOfSize:14 weight:UIFontWeightSemibold];
        cell.contentView.backgroundColor = [[UIColor colorWithHexString:@"#000000"] colorWithAlphaComponent:0.04];
        cell.contentView.layer.masksToBounds = true;
        cell.contentView.layer.cornerRadius = 25;
    } else {
        cell.textLabel.textColor = [[UIColor colorWithHexString:@"#000000"] colorWithAlphaComponent:0.5];
        cell.textLabel.font = [UIFont systemFontOfSize:13 weight:UIFontWeightRegular];
        cell.contentView.backgroundColor = [UIColor clearColor];
    }
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    // 如果点击的是当前选中的cell，不做处理
    if ([indexPath isEqual:self.selectedIndexPath]) {
        return;
    }
    
    // 保存之前选中的indexPath用于刷新
    NSIndexPath *previousIndexPath = self.selectedIndexPath;
    
    // 更新选中的indexPath
    self.selectedIndexPath = indexPath;
    
    // 刷新之前选中的cell和当前选中的cell
    if (previousIndexPath) {
        [tableView reloadRowsAtIndexPaths:@[previousIndexPath, indexPath]
                         withRowAnimation:UITableViewRowAnimationNone];
    } else {
        [tableView reloadRowsAtIndexPaths:@[indexPath]
                         withRowAnimation:UITableViewRowAnimationNone];
    }
    
    // 可选：滚动到选中的cell
    [tableView scrollToRowAtIndexPath:indexPath
                     atScrollPosition:UITableViewScrollPositionMiddle
                             animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}

#pragma mark - Button Action

- (void)clickConfirmBtnAction {
    if (self.selectedIndexPath) {
        PersonalEveryablyModel *selectedModel = self.personalBlackModel.everyably[self.selectedIndexPath.row];
        NSLog(@"选中了: %@", selectedModel.quindecimlocalety);
        if (self.delegate && [self.delegate respondsToSelector:@selector(enumCustomView:didSelectItemAtIndex:model:)]) {
            [self.delegate enumCustomView:self didSelectItemAtIndex:self.selectedIndexPath.row model:selectedModel];
        }
    }
}

#pragma mark - Public Methods

// 获取当前选中的模型
- (PersonalEveryablyModel *)selectedModel {
    if (self.selectedIndexPath && self.selectedIndexPath.row < self.personalBlackModel.everyably.count) {
        return self.personalBlackModel.everyably[self.selectedIndexPath.row];
    }
    return nil;
}

// 获取当前选中的索引
- (NSInteger)selectedIndex {
    return self.selectedIndexPath ? self.selectedIndexPath.row : -1;
}

@end
